package biznussoft.metercor.fragments;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;

import org.json.JSONArray;
import org.json.JSONObject;

import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.Fragment;
import android.support.v4.view.MenuItemCompat;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
import biznussoft.metercor.MainActivity;
import biznussoft.metercor.R;
import biznussoft.metercor.entity.AccountModel;
import biznussoft.metercor.entity.ContactsModel;
import biznussoft.metercor.listener.Globallistener;
import biznussoft.metercor.utils.CustomProgressDialog;
import biznussoft.metercor.utils.Session;

import com.google.gson.Gson;
import com.salesforce.androidsdk.rest.RestClient;
import com.salesforce.androidsdk.rest.RestClient.AsyncRequestCallback;
import com.salesforce.androidsdk.rest.RestRequest;
import com.salesforce.androidsdk.rest.RestResponse;
import com.salesforce.androidsdk.util.EventsObservable;
import com.salesforce.androidsdk.util.EventsObservable.EventType;

public class AccountsFragment  extends Fragment implements OnItemClickListener{

	private Dialog progressDialog; 
	private RestClient client;
	ArrayList<ContactsModel> contactsList;
	public static ArrayList<AccountModel> list;
	public static HashMap<String, ArrayList<ContactsModel>> subContactsList;
	private Globallistener mHomeItemListener;        
	private ListView lv;
	
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		return inflater.inflate(R.layout.service_order_records, null);                  
	}         

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setHasOptionsMenu(true);

	}
	@Override
	public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
		MenuItem addAccount = menu.add("New");
		MenuItemCompat.setShowAsAction(addAccount, MenuItemCompat.SHOW_AS_ACTION_ALWAYS | MenuItemCompat.SHOW_AS_ACTION_WITH_TEXT);
		addAccount.setIcon(R.drawable.add); 
		super.onCreateOptionsMenu(menu, inflater);
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		
		 if(item.getTitle().equals("New")){
				
			 //AccountDetailsFragment newFragment = new AccountDetailsFragment();
			 getActivity().getSupportFragmentManager().beginTransaction().add(R.id.account, new AccountDetailsFragment()).commit();

			new Handler().postDelayed(new Runnable() {
	            @Override
	            public void run() {
	            	AccountDetailsFragment  fragment = (AccountDetailsFragment)  getActivity().getSupportFragmentManager().findFragmentById(R.id.account);       
	            	fragment.newAccount();	            }
	        }, 1000);
			
			mHomeItemListener.getSignature("AccountInsert");
		 }
		return super.onOptionsItemSelected(item);
		
	}
	@Override
	public void onAttach(Activity activity) {
		super.onAttach(activity);
		mHomeItemListener = (Globallistener) (activity);
	}

	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		super.onActivityCreated(savedInstanceState);
		lv = (ListView) getView().findViewById(R.id.listview);
		lv.setOnItemClickListener(this);      
		client =  MainActivity.mActivity.client;
		AccountModel.api_Version = getString(R.string.api_version);

		progressDialog = CustomProgressDialog
				.getInstance().createProgressDialog(getActivity());
		progressDialog.setCanceledOnTouchOutside(false);
		progressDialog.show();      
		retriveLeads();
	}

	

	public void retriveLeads()                            
	{
		try{        
			
			String accounts = "SELECT Parent_Account__c,Id,Name,Fax,AccountNumber,AnnualRevenue,Type,Industry,ParentId,NumberOfEmployees,Rating,Website,Phone,Ownership,BillingStreet,BillingCity,BillingState,BillingPostalCode,BillingCountry,ShippingStreet,ShippingCity,ShippingState, ShippingPostalCode,ShippingCountry,(Select id,LastName,FirstName,AccountId,Title,Phone,MobilePhone,Email,MailingStreet,MailingCity,MailingState,MailingCountry,MailingPostalCode,OtherStreet,OtherCity,OtherState,OtherPostalCode,OtherCountry from Contacts) FROM Account";


			RestRequest restRequest = RestRequest.getRequestForQuery(getString(R.string.api_version), accounts);

			client.sendAsync(restRequest, new AsyncRequestCallback() {  
				@Override
				public void onSuccess(RestRequest request, RestResponse result) {
					try {      
						progressDialog.dismiss();
						Log.i("NCS","RestResponse  is  :"+result.toString());
						JSONObject jsonObject1 = new JSONObject(result.asString());

						JSONArray jsonArray = jsonObject1.getJSONArray("records");

						list = new ArrayList<AccountModel>();
						subContactsList = new HashMap<String, ArrayList<ContactsModel>>();
						Gson _gson = new Gson();
						for(int i=0; i< jsonArray.length(); i++)
						{
							contactsList = new ArrayList<ContactsModel>();
							if(!jsonArray.isNull(i)){
								AccountModel bean = _gson.fromJson(jsonArray.getString(i), AccountModel.class);
								String ID = jsonArray.getJSONObject(i).getString("Id");
								list.add(bean);
								try{
									JSONObject contacts = jsonArray.getJSONObject(i).getJSONObject("Contacts");
									JSONArray contactsArray = contacts.getJSONArray("records");

									Gson contactsList_gson = new Gson();
									for(int j=0; j< contactsArray.length(); j++)
									{
										if(!contactsArray.isNull(j)){
											ContactsModel contactbean = contactsList_gson.fromJson(contactsArray.getString(j), ContactsModel.class);
											contactsList.add(contactbean);


										}
									}

									subContactsList.put(ID, contactsList);


								}catch(Exception e){
									Log.i("NCS","Contacts Exception   is  :"+e.getMessage());
								}
							}
						}

						showRecords();

					} catch (Exception e) {
						onError(e);
					}
				}

				@Override
				public void onError(Exception exception) {
					EventsObservable.get().notifyEvent(EventType.RenditionComplete);
				}
			});



		} catch (Exception e) {
			Log.i("NCS","Exception  2 is  :"+e.getMessage());
		}

	}
	class ListComparator implements Comparator<AccountModel>,Serializable
	{
	public int compare(AccountModel o1, AccountModel o2)
	{

	return o1.getName().compareTo(o2.getName());

	}

	}

	public void showRecords(){
		Collections.sort(list, new ListComparator());
		AccountMasterAdapter adapter = new AccountMasterAdapter(getActivity(),list);
		lv.setAdapter(adapter);                        
	}

	public void onItemClick(AdapterView<?> arg0, View arg1, int position, long arg3) {
		/*setHasOptionsMenu(false);
		mHomeItemListener.getResponse(position);*/
	}

	class AccountMasterAdapter extends BaseAdapter {
		boolean checkArray[]; 	
		ArrayList<AccountModel> listdata;
		Context mContext;

		public AccountMasterAdapter(Context context, ArrayList<AccountModel> list) {
			// TODO Auto-generated constructor stub
			this.listdata = list;
			this.mContext = context;
			checkArray = new boolean[list.size()];
		}

		public int getCount() {
			// TODO Auto-generated method stub
			return listdata.size();
		}

		public Object getItem(int position) {
			// TODO Auto-generated method stub
			return null;
		}

		public long getItemId(int position) {
			// TODO Auto-generated method stub
			return 0;
		}
		
		public class ViewHolder{
			public TextView name;    
			public TextView phno;
//			public TextView billingCity;
			public ImageView image;
			public RelativeLayout rLayout;
		}

		public View getView(final int position, View v, ViewGroup parent) {
			// TODO Auto-generated method stub
			
			ViewHolder holder;
			
			if(v == null){
				
				holder = new ViewHolder();
				LayoutInflater inflator = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
				v = inflator.inflate(R.layout.common_details_page, null);
				holder.name  = (TextView) v.findViewById(R.id.text1);
//				holder.billingCity  = (TextView) v.findViewById(R.id.text2);
				holder.phno = (TextView) v.findViewById(R.id.text2);
				holder.image = (ImageView) v.findViewById(R.id.imageview);
				holder.rLayout  = (RelativeLayout) v.findViewById(R.id.rrlayout_1);
				v.setTag(holder);
			}else{
				holder = (ViewHolder) v.getTag();
				 holder.image.setImageResource(R.drawable.account_tabs_bg);
			}
			
			
			  v.setTag(holder);
		      holder.rLayout.setId(position);
			
			
			
			final AccountModel bean = listdata.get(position);
			
				holder.name.setText(bean.getName());
//				holder.billingCity.setText(bean.getBillingCity());
				holder.phno.setText(bean.getPhno());
				//holder.image.setImageResource(R.drawable.account_tabs_bg);
				
				
				holder.rLayout.setOnClickListener(new OnClickListener() {
					
					@Override
					public void onClick(View v) {
						
						setHasOptionsMenu(false);
						mHomeItemListener.getResponse(position);
						Session.sAccountName = bean.getName();
						Session.sParentId= bean.getId();                  
						
						for (int i = 0; i <listdata.size(); i++) {
		                    if (v.getId() == i) {
		                    	checkArray[i] = true;
		                    } else {
		                    	checkArray[i] = false;
		                    }
		                }
		                notifyDataSetChanged();
		            }
					
				});           
				
				if (checkArray[position]) {  
		            holder.image.setImageResource(R.drawable.active_account_bg);
		        } else {
		            holder.image.setImageResource(R.drawable.account_tabs_bg);
		        }
			
			return v;
		}

	}

}

